<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends Controller {
    public function getChilds($data,$uid,$arr){//获所有下级，只有账号
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                unset($data[$k]);
                $arr[]=$v['user_id'];
                $arr=$this->getChilds($data,$v['user_id'],$arr);
            }
        }
        return $arr;
    }

    public function getChildsClass($data,$uid,$arr,$n){//获取下线层级,用户信息
        $n++;
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                $v['class']=$n;
                $arr[]=$v;
                unset($data[$k]);
                $arr=$this->getChildsClass($data,$v['user_id'],$arr,$n);
            }
        }
        return $arr;
    }

    public function getSuperior($array,$agent,$arr){//获取上线
        foreach ($array as $k => $v){
            if($agent==$v['user_id']){
                $arr[]=$v;
                unset($array[$k]);
                $arr=$this->getSuperior($array,$v['user_recommend'],$arr);break;
            }
        }
        return $arr;
    }

    public function index(){//用户列表
        $status=I('status') ? I('status') : 0;
        $account=I('account') ? I('account') : 0;
        $where='(user_role=1)';
        if(!empty($status)){
            $where.='and (status='.$status.') ';
        }
        if(!empty($account)){
            $where.='and ((user_id=\''.$account.'\') or (user_email=\''.$account.'\') or (user_phone=\''.$account.'\') or (user_cards=\''.$account.'\') or (user_recommend=\''.$account.'\'))';
        }
        $model = M('user');
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count,20);
        $Page->parameter['status']=$status;
        $Page->parameter['account']=$account;
        $show = $Page->show();
        $list = $model->field('user_id,user_name,user_recommend,user_cards,user_email,user_phone,user_createtime,city,country,status,province,card_type')
            ->where($where)->order('user_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('status',$status);
        $this->assign('account',$account);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function userDetail(){//用户详情
        $id=I('id') ? I('id') : die('{\'status\':0,\'msg\':\'非法操作\'}');
        $model=M('user');
        $msg=$model->field('user.*,position.user_position')
            ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
        $mt4_msg=M('mt4_users','','DB_CONFIG2')->field('LOGIN,GROUP,ENABLE_CHANGE_PASS,ENABLE,ENABLE_READONLY,SEND_REPORTS,BALANCE')->where(['LOGIN'=>$id])->find();
        $mt4_msg['tradingblocked']=$mt4_msg['enable_readonly'];
        $mt4_msg['enableChangePassword']=$mt4_msg['enable_change_pass'];

        /*$request="action=getaccountinfoex&login=".$id."\0";
        $return = mt4_operation($request);
        parse_str($return,$mt4_msg);*/
        $group_type=M('mt4_groups')->field('type')->where(['mt4_group'=>$msg['group']])->find();
        $group=M('mt4_groups')->field('id,mt4_group,type')->where(['type'=>$group_type['type']])->select();//查询相同类型的组别
        $position=M('position')->field('id,user_position')->order('id desc')->select();//查询职位
        //结构图组装
        /*$users=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
        $self=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
        $list=$this->getChildsClass($users,$id,[],0);
        $str='<ul><li class="jstree-open">MT4 : '.$self['user_id'].' Position : '.$self['user_position'].' Class : 0';
        //$tree=$this->getChildsTree($list,$id,$self);//拼装为数组
        $tree=$this->getChildsTree2($list,$id,$str);//拼装为HTML
        $tree.='</li></ul>';*/

        //上线结构
        $maxSuperior=[];
        $userAll=$model->field('user_id,user_recommend,user_name,position,group')->select();//查询所有人
        $superior=$this->getSuperior($userAll,$msg['user_recommend'],[]);
        foreach ($superior as $k => $v){
            if($v['user_recommend']==0){
                $maxSuperior=$v;break;
            }
        }
        foreach ($position as $k => $v){
            if($maxSuperior['position']==$v['id']){
                $maxSuperior['user_position']=$v['user_position'];
            }
            foreach ($superior as $ke => $va){
                if($v['id']==$va['position']){
                    $position[$k]['child']=$va;break;
                }
            }
        }
        foreach ($superior as $k => $v){
            foreach ($position as $ke => $va){
                if($v['position']==$va['id']){
                    $superior[$k]['user_position']=$va['user_position'];break;
                }
            }
        }
        //print_r($superior);
        //查询未到期的航线币
        /*$firstday = date("Y-m-d");
        $last_month=strtotime($firstday." -1 month")+1;
        $currentday = date("Y-m-0");
        $current_month=strtotime($currentday);
        $airline=M('into_gold')->where('into_time >'.$last_month)->sum('final_money');//未到期总和
        $airline_current=M('into_gold')->where('into_time >'.$current_month)->sum('final_money');//本月总和
        $rate1=M('into_gold_set')->field('rate')->where(['type'=>1,'state'=>1])->find();//本月
        $rate2=M('into_gold_set')->field('rate')->where(['type'=>2,'state'=>1])->find();//上月
        if($mt4_msg['balance']>$airline){
            $rate=($mt4_msg['balance']-($airline-$airline_current))*$rate1['rate']+($airline-$airline_current)*$rate2['rate'];
        }else if($mt4_msg['balance']>$airline_current){
            $rate=($mt4_msg['balance']-$airline_current)*$rate2['rate']+($airline_current*$rate1['rate']);
        }else{
            $rate=$mt4_msg['balance']*$rate1['rate'];
        }*/
        $rate1=M('gold_set')->field('rate,fee')->where(['type'=>1,'state'=>1])->find();
        $rate=($mt4_msg['balance']-$mt4_msg['balance']*$rate1['fee'])*$rate1['rate'];
        $this->assign('rate',$rate);
        $this->assign('maxSuperior',$maxSuperior);
        $this->assign('superior',$superior);
        $this->assign('position',$position);
        $this->assign('group_type',$group_type['type']);
        $this->assign('group',$group);
        $this->assign('msg',$msg);
        //$this->assign('tree',$tree);//结构图
        $this->assign('mt4_msg',$mt4_msg);
        $this->display();
    }

    public function getTree(){//获取用户结构图-全部获取，用户量少的时候使用
        $id=I('id') ? I('id') : die('{\'status\':0,\'msg\':\'非法操作\'}');
        $model=M('user');
        //结构图组装
        $users=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
        $self=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
        $list=$this->getChildsClass($users,$id,[],0);
        $str='<ul><li class="jstree-open">MT4 : '.$self['user_id'].' Position : '.$self['user_position'].' Class : 0';
        //$tree=$this->getChildsTree($list,$id,$self);//拼装为数组
        $tree=$this->getChildsTree2($list,$id,$str);//拼装为HTML
        $tree.='</li></ul>';
        $this->assign('tree',$tree);
        $this->display();
    }

    public function getTree2(){//获取用户结构图-分批获取，用户量大的时候使用
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('user');
        $users=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where('user.user_recommend = '.$id)->select();
        if(empty($users)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'到底了！！！'));
        }else{
            $logins=[];
            foreach($users as $k => $v){
                $logins[]=$v['user_id'];
            }
            $agents=$model->field('distinct user_recommend')->where('user_recommend in ('.implode(',',$logins).')')->select();
            foreach($users as $k => $v){
                $users[$k]['hasChild']=0;
                foreach ($agents as $ke => $va){
                    if($v['user_id']==$va['user_recommend']){
                        $users[$k]['hasChild']=1;break;
                    }
                }
            }
            $this->ajaxReturn(array('status'=>1,'msg'=>$users));
        }
    }

    function getMonthNum( $date1, $date2, $tags='-' ){
        $date1 = explode($tags,$date1);
        $date2 = explode($tags,$date2);
        return ($date1[0] - $date2[0])*12+($date1[1] - $date2[1]);
    }

    public function getBalance(){//获取用户余额
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $request="action=getaccountinfoex&login=".$id."\0";
        $return = mt4_operation($request);
        parse_str($return,$mt4_msg);
        if($mt4_msg['result']==1){
            //查询未到期的航线币
            /*$firstday = date("Y-m-d");
            $last_month=strtotime($firstday." -1 month")+1;
            $currentday = date("Y-m-0");
            $current_month=strtotime($currentday);
            $airline=M('into_gold')->where('into_time >'.$last_month)->sum('final_money');//未到期总和
            $airline_current=M('into_gold')->where('into_time >'.$current_month)->sum('final_money');//本月总和
            $rate1=M('into_gold_set')->field('rate')->where(['type'=>1,'state'=>1])->find();//本月
            /*$rate2=M('into_gold_set')->field('rate')->where(['type'=>2,'state'=>1])->find();//上月
            if($mt4_msg['balance']>$airline){
                $mt4_msg['balanceAir']=($mt4_msg['balance']-($airline-$airline_current))*$rate1['rate']+($airline-$airline_current)*$rate2['rate'];
            }else if($mt4_msg['balance']>$airline_current){
                $mt4_msg['balanceAir']=($mt4_msg['balance']-$airline_current)*$rate2['rate']+($airline_current*$rate1['rate']);
            }else{
                $mt4_msg['balanceAir']=$mt4_msg['balance']*$rate1['rate'];
            }*/
            $rate1=M('gold_set')->field('rate,fee')->where(['type'=>1,'state'=>1])->find();
            $mt4_msg['balanceAir']=($mt4_msg['balance']-$mt4_msg['balance']*$rate1['fee'])*$rate1['rate'];
            $this->ajaxReturn(array('status'=>1,'msg'=>$mt4_msg));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'获取失败请重试'));
        }
    }

    public function updateUserInfo(){//修改用户基本资料
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['user_state']=I('post.user_state') ? I('post.user_state') : die(json_encode(array('status'=>0,'msg'=>'请设置账户状态')));
        $data['position']=I('post.position') ? I('post.position') : die(json_encode(array('status'=>0,'msg'=>'请设置用户职位')));
        $data['user_recommend']=I('post.user_recommend') ? I('post.user_recommend') : 0;
        $data['user_name']=I('post.user_name') ? I('post.user_name') : die(json_encode(array('status'=>0,'msg'=>'请输入英文名字')));
        $data['name_zh_cn']=I('post.name_zh_cn') ? I('post.name_zh_cn') : die(json_encode(array('status'=>0,'msg'=>'请输入中文姓名')));
        $data['weixin']=I('post.weixin') ? I('post.weixin') : '';
        $data['city']=I('post.city') ? I('post.city') : die(json_encode(array('status'=>0,'msg'=>'请输入城市')));
        $data['province']=I('post.province') ? I('post.province') : die(json_encode(array('status'=>0,'msg'=>'请输入省份')));
        $data['user_address']=I('post.user_address') ? I('post.user_address') : '';
        $data['zipcode']=I('post.zipcode') ? I('post.zipcode') : die(json_encode(array('status'=>0,'msg'=>'请输入邮政编码')));
        $data['user_phone']=I('post.user_phone') ? I('post.user_phone') : die(json_encode(array('status'=>0,'msg'=>'请输入电话')));
//        $data['user_email']=I('post.user_email') ? I('post.user_email') : die(json_encode(array('status'=>0,'msg'=>'请输入邮箱')));
        $data['user_qq']=I('post.user_qq') ? I('post.user_qq') : '';
        $data['sex']=I('post.sex') ? I('post.sex') : die(json_encode(array('status'=>0,'msg'=>'请选择性别')));
        $data['card_type']=I('post.card_type') ? I('post.card_type') : die(json_encode(array('status'=>0,'msg'=>'请选择证件类型')));
        $data['user_cards']=I('post.user_cards') ? I('post.user_cards') : die(json_encode(array('status'=>0,'msg'=>'请输入证件号码')));
        //$data['user_birthday']=I('post.user_birthday') ? I('post.user_birthday') : '';
        $model=M('user');
        $user=$model->field('user_recommend')->where(['user_id'=>$id])->find();
        if(($data['user_recommend']!=0)&&($data['user_recommend']!=$user['user_recommend'])){
            if($data['user_recommend']==$id){//判断代理人是否为自己
                $this->ajaxReturn(array('status'=>0,'msg'=>'代理人不可以是自己'));
            }
            $users=$model->field('user_id,user_recommend')->where('user_recommend >0')->select();
            $childs=$this->getChilds($users,$id,[]);
            if(in_array($data['user_recommend'],$childs)){//判断代理人是否为自己下线
                $this->ajaxReturn(array('status'=>0,'msg'=>'代理人不可以是自己下线'));
            }
        }
        $model->startTrans();
        $res=$model->where(['user_id'=>$id])->save($data);
        $request = "action=modifyaccount&login=".$id."&name=".$data['user_name']."&agent=".$data['user_recommend']."&address=".$data['user_address']."&phone=".$data['user_phone']."&id=".$data['user_cards']."&zipcode=".$data['zipcode']."&city=".$data['city']."&country=".$data['country']."\0";
        $return=mt4_operation($request);
        parse_str($return,$res2);
        if(($res2['result']==1)&&($res!==false)){
            $model->commit();
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $model->rollback();
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function examine(){//审核
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['status']=I('post.type') ? I('post.type') : die(json_encode(array('status'=>0,'msg'=>'未知操作')));
        $reason=I('post.reason') ? I('post.reason') : '';
        if(($data['status']==4) && empty($reason)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'请填写拒绝理由'));
        }
        $res=M('user')->where(['user_id'=>$id])->save($data);
        if($res!==false){
            if($data['status']==3){//通过
                $type=10004;//邮件模板编号
                $user=M('user')->field('user_email')->where(['user_id'=>$id])->find();
                $email=M('mail_mould')->where(['type'=>$type])->find();
                $mail_msg = str_replace('{1}',$id,$email['content']);
                $send=@SendMail($user['user_email'],$email['title'],htmlspecialchars_decode($mail_msg));
            }else if($data['status']==4){//未通过
                $type=10005;//邮件模板编号
                $user=M('user')->field('user_email')->where(['user_id'=>$id])->find();
                $email=M('mail_mould')->where(['type'=>$type])->find();
                $mail_msg = str_replace('{1}',$id,$email['content']);
                $mail_msg = str_replace('{2}',$reason,$mail_msg);
                $send=@SendMail($user['user_email'],$email['title'],htmlspecialchars_decode($mail_msg));
            }
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function updatePwd(){//重置密码
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $pwd=I('post.pwd') ? I('post.pwd') : die(json_encode(array('status'=>0,'msg'=>'请输入密码')));
        $repwd=I('post.repwd') ? I('post.repwd') : die(json_encode(array('status'=>0,'msg'=>'请确认密码')));
        if($pwd!=$repwd){
            $this->ajaxReturn(array('status'=>0,'msg'=>'确认密码不一致'));
        }
        $data['user_password']=md5(md5($pwd));
        $res=M('user')->where(['user_id'=>$id])->save($data);
        if($res){
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function updateMt4Data(){//修改mt4信息
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $enableChangePassword=I('post.enable_change_pass') ? I('post.enable_change_pass') : 0;
        $enable=I('post.enable') ? I('post.enable') : 0;
        $enable_read_only=I('post.enable_readonly') ? I('post.enable_readonly') : 0;
        $send_reports=I('post.send_reports') ? I('post.send_reports') : 0;
        $request = "action=modifyaccount&login=".$id."&enable_change_password=".$enableChangePassword."&enable=".$enable."&enable_read_only=".$enable_read_only."&send_reports=".$send_reports."\0";
        $return=mt4_operation($request);
        parse_str($return,$res);
        if($res['result']==1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function updateGroup(){//修改组别
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['group']=I('post.group') ? I('post.group') : die(json_encode(array('status'=>0,'msg'=>'请选择组别')));
        $node=I('post.node') ? I('post.node') : die(json_encode(array('status'=>0,'msg'=>'请设置要修改的节点')));
        $model=M('user');
        $childs=[];
        if($node==3){
            $users=$model->field('user_id,user_recommend')->where('user_recommend >0')->select();
            $childs=$this->getChilds($users,$id,[]);
        }else if($node==2){
            $users=$model->field('user_id')->where('user_recommend='.$id)->select();
            foreach ($users as $k => $v){
                $childs[]=$v['user_id'];
            }
        }
        $childs[]=$id;
        $model->startTrans();
        $res=$model->where('user_id in ('.implode(',',$childs).')')->save($data);
        $request="action=bulkmodifyaccount&login=".implode(';',$childs)."&group=".$data['group']."\0";
        $return=mt4_operation($request);
        parse_str($return,$res2);
        if(($res2['result']==1)&&($res!==false)){
            $model->commit();
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $model->rollback();
            $this->ajaxReturn(array('status'=>0,'msg'=>$res2));
        }
    }

    public function updateLeverage(){//修改杠杆
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['level']=I('post.leverage') ? I('post.leverage') : die(json_encode(array('status'=>0,'msg'=>'请选择杠杆比例')));
        $node=I('post.node') ? I('post.node') : die(json_encode(array('status'=>0,'msg'=>'请设置要修改的节点')));
        $model=M('user');
        $childs=[];
        if($node==3){
            $users=$model->field('user_id,user_recommend')->where('user_recommend >0')->select();
            $childs=$this->getChilds($users,$id,[]);
        }else if($node==2){
            $users=$model->field('user_id')->where('user_recommend='.$id)->select();
            foreach ($users as $k => $v){
                $childs[]=$v['user_id'];
            }
        }
        $childs[]=$id;
        $model->startTrans();
        $res=$model->where('user_id in ('.implode(',',$childs).')')->save($data);
        $request="action=bulkmodifyaccount&login=".implode(';',$childs)."&leverage=".$data['level']."\0";
        $return=mt4_operation($request);
        parse_str($return,$res2);
        if(($res2['result']==1)&&($res!==false)){
            $model->commit();
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $model->rollback();
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function updateMt4Pwd(){//修改MT4密码
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $pass=I('post.mt4_pwd') ? I('post.mt4_pwd') : die(json_encode(array('status'=>0,'msg'=>'请输入mt4密码')));
        $investor=I('post.investor') ? I('post.investor') : 0;
        if(empty($investor)){
            $request = "action=changepassword&login=".$id."&pass=".$pass."\0";
        }else{
            $request = "action=changepassword&login=".$id."&pass=".$pass."&investor=".$investor."\0";
        }
        $return=mt4_operation($request);
        parse_str($return,$res);
        if($res['result']==1){
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function updateBalance(){//type:1-入金，2-取款
        $admin=session('admin');
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $type=I('post.type') ? I('post.type') : die(json_encode(array('status'=>0,'msg'=>'非法操作2')));
        $money=I('post.money') ? I('post.money') : die(json_encode(array('status'=>0,'msg'=>'请设置金额')));
        $comment=I('post.comment') ? I('post.comment') : die(json_encode(array('status'=>0,'msg'=>'请填写注释')));
        $setType='';
        if($type==1){
            if($admin['user_role']<4){
                $this->ajaxReturn(array('status'=>0,'msg'=>'您没有该权限'));
            }
            $str='deposit';
        }else if($type==3){
            $setType=I('post.setType') ? I('post.setType') : die(json_encode(array('status'=>0,'msg'=>'请选择操作类型')));
            if($setType==2){
                $str='deposit';
                if($money<0){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'解冻金额为正数'));
                }
            }else{
                $str='withdrawal';
                if($money>0){
                    $this->ajaxReturn(array('status'=>0,'msg'=>'冻结金额为负数'));
                }
            }
        }else{
            $str='withdrawal';
        }
        if(substr($comment,0,strlen($str))!==$str){
            $this->ajaxReturn(array('status'=>0,'msg'=>'注释不正确'));
        }
        $model=M('user');
        if($type==3){
            $mt4_msg=M('mt4_users','','DB_CONFIG2')->field('BALANCE')->where(['LOGIN'=>$id])->find();
            if(($mt4_msg['balance']<$money)&&($setType==1)){
                $this->ajaxReturn(array('status'=>0,'msg'=>'用户余额不足，无法冻结'));
            }
            $model->startTrans();
            $set=$model->where(['user_id'=>$id])->setInc('frozen_balance',(-1*$money));//abs($money)
            if($set===false){
                $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败,请重试'));
            }
        }
        $request = "action=changebalance&login=".$id."&value=".$money."&comment=".$comment."\0";//bulkchangebalance-批量修改bulk
        $return=mt4_operation($request);
        parse_str($return,$res);
        if($res['result']==1){
            $model->commit();
            //$balance=explode(';',$res['size']);$balance[1]
            if($type==3){$user=$model->field('frozen_balance')->where(['user_id'=>$id])->find();}
            $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功','balance'=>$res['newbalance'],'frozen_balance'=>$user['frozen_balance']));
        }else{
            $model->rollback();
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }

    public function getChildsTree($array,$uid,$arr){//获取下线树-数组
        foreach ($array as $k => $v){
            if($uid==$v['user_recommend']){
                unset($array[$k]);
                $arr['child'][]=$this->getChildsTree($array,$v['user_id'],$v);
            }
        }
        return $arr;
    }

    public function getChildsTree2($array,$uid,$str){//获取下线树-HTML
        $str.='<ul>';
        foreach ($array as $k => $v){
            if($uid==$v['user_recommend']){
                unset($array[$k]);
                $group=$this->getChildsTree2($array,$v['user_id'],'');
                $type='';
                if($group=='<ul></ul>'){
                    $type='data-jstree=\'{"type":"html"}\'';
                }
                $str.='<li '.$type.'>MT4 : '.$v['user_id'].' Position : '.$v['user_position'].' Class : '.$v['class'].''.$group.'</li>';
            }
        }
        return $str.'</ul>';
    }

    public function userTree(){//结构图测试
//        $id=52379;
        $id=I('id') ? I('id') : die('{\'status\':0,\'msg\':\'非法操作\'}');
        $model=M('user');
        $users=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
        $self=$model->field('user.user_id,user.user_recommend,user.user_name,position.user_position')
            ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
        $list=$this->getChildsClass($users,$id,[],0);
        $str='<ul><li class="jstree-open">MT4 : '.$self['user_id'].' Position : '.$self['user_position'].' Class : 0';
        //$tree=$this->getChildsTree($list,$id,$self);
        $tree=$this->getChildsTree2($list,$id,$str);
        $tree.='</li></ul>';
        print_r($tree);
    }

    public function downloadTree(){//下载结构图
        $id=I('id') ? I('id') : die('{\'status\':0,\'msg\':\'非法操作\'}');
        $model=M('user');
        $users=$model->field('user.user_id,user.user_name,user.user_recommend,user.user_email,position.user_position,user.level')
            ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
        $self=$model->field('user.user_id,user.user_name,user.user_recommend,user.user_email,position.user_position,user.level')
            ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
        $arr[]=$self;
        $list=$this->getChildsClass($users,$id,$arr,0);
        $csv=new \Think\Csv();
        $csv_title=array('ID','Name','Agent','Email','	Position','Leverage','Class');
        $csv->put_csv($list,$csv_title);
    }
}